package com.banquetmanagementsystem.service.impl;

import com.banquetmanagementsystem.common.Utils.TokenUtil;
import com.banquetmanagementsystem.common.Utils.TokenUtilProperties;
import com.banquetmanagementsystem.mapper.RefreshTokenMapper;
import com.banquetmanagementsystem.pojo.entity.RefreshToken;
import com.banquetmanagementsystem.service.NewTokenService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @author 86176
 */
@Service
public class NewTokenServiceImpl implements NewTokenService {
    @Resource(name = "refreshTokenMapper")
    private RefreshTokenMapper refreshTokenMapper;
    @Resource(name = "tokenUtil")
    private TokenUtil tokenUtil;
    @Resource(name = "tokenUtilProperties")
    private TokenUtilProperties tokenUtilProperties;
    @Override
    public Map<String, String> newToken(Map<String, String> claims,Integer userId) {
        //签发长时效token
        boolean isWeeklyDurationEnabled = Boolean.parseBoolean(claims.get("isWeeklyDurationEnabled"));
        String refreshToken = tokenUtil.getRefreshToken(claims, isWeeklyDurationEnabled);
        RefreshToken refreshTokenEntity = new RefreshToken();
        refreshTokenEntity.setRefreshToken(refreshToken);
        refreshTokenEntity.setUserId(userId);
        Integer i = refreshTokenMapper.updateRefreshToken(refreshTokenEntity);
        if (i==null){
            refreshTokenMapper.insertRefreshToken(refreshTokenEntity);
        }
        //签发短时效token
        String accessToken = tokenUtil.getAccessToken(claims);
        Map<String,String> tokenMap = new HashMap<>(2);
        tokenMap.put(tokenUtilProperties.getRefreshTokenName(), refreshToken);
        tokenMap.put(tokenUtilProperties.getAccessTokenName(),accessToken);
        return tokenMap;
    }
}
